package com.jeesit.cloud.spot.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 * @author syd
 */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Bean(value = "executor")
    @Override
    public Executor getAsyncExecutor() {
        //线程池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //线程池的基本大小
        taskExecutor.setCorePoolSize(100);
        //线程池中允许的最大线程数
        taskExecutor.setMaxPoolSize(200);
        //线程池所使用的缓冲队列
        taskExecutor.setQueueCapacity(200);
        //线程池维护线程所允许的空闲时间
        taskExecutor.setKeepAliveSeconds(60);
        //线程名称前缀
        taskExecutor.setThreadNamePrefix("task-");
        //线程是否等待当前被调度的任务完成
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        //线程等待时长
        taskExecutor.setAwaitTerminationSeconds(60);
        //设置拒绝任务的处理器
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}
